package cn.shenxingbang.chatroom.controller;

import cn.shenxingbang.chatroom.config.MyServerEndpointConfigurator;
import cn.shenxingbang.chatroom.entity.UserChat;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
@Component
@ServerEndpoint(value = "/websocket", configurator = MyServerEndpointConfigurator.class)
public class WebSocketController {

    private static final ObjectMapper jackson = new ObjectMapper();

    private static final String url = "http://127.0.0.1:8081";
    /*ws://127.0.0.1:8081/websocket*/

    private static CopyOnWriteArrayList<WebSocketController> webSocketSet = new CopyOnWriteArrayList<>();

    private RestTemplate restTemplate = new RestTemplate();

    private Session session;

    /**
     * 主要用来做历史聊天记录中“我”和“其他人”的身份区分。
     */
    private String ip;

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) throws Throwable {
        session.setMaxIdleTimeout(1000 * 60 * 60);
        this.session = session;
        webSocketSet.add(this);
        log.info("--[开启，当前连接数：{}]", webSocketSet.size());

        ip = config.getUserProperties().get("realIP").toString();
        /*InetSocketAddress remoteAddress = WebsocketUtil.getRemoteAddress(session); ip = remoteAddress.getHostString();*/

        UserChat[] userChats = restTemplate.getForObject(url + "/findAllUser", UserChat[].class);
        List<UserChat> chatList = Arrays.asList(userChats);
        for (UserChat i : chatList){
            if (i.getIp().equals("0.0.0.0") || i.getIp().equals(ip)) i.setIsSelf(1);
        }

        session.getAsyncRemote().sendText(jackson.writeValueAsString(chatList));
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("--[关闭，当前连接数：{}]", webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String msg, Session session) throws Throwable {

        UserChat userChat = jackson.readValue(msg, UserChat.class);

        if (userChat.getNickname().equals("")) userChat.setNickname("匿名用户");
        userChat.setDate(new Date());
        if (userChat.getNickname().length() > 30)
            userChat.setNickname(userChat.getNickname().subSequence(0, 29).toString());

        String sendToOthers = jackson.writeValueAsString(userChat);
        userChat.setIsSelf(1);
        String sendToMyself = jackson.writeValueAsString(userChat);
        broadcast(sendToMyself, sendToOthers, session.getId(), userChat.getNickname());

        //入库操作
        userChat.setIp(ip);
        restTemplate.postForEntity(url + "/insert", userChat, String.class);

    }

    @OnError
    public void onError(Session session, Throwable e) {
        e.printStackTrace();
    }

    /**
     * 最大字符数：8157
     * @param sendToMyself
     * @param sendToOthers
     * @param id
     * @param nickName
     */
    public void broadcast(String sendToMyself, String sendToOthers, String id, String nickName) {

        for (WebSocketController item : webSocketSet) {
            if (item.session.equals(session)) item.session.getAsyncRemote().sendText(sendToMyself);
            else
                item.session.getAsyncRemote().sendText(sendToOthers);
        }
        log.info("--[id：{}，用户昵称：{}，发送消息：{}]", id, nickName, sendToOthers);
    }

    @Bean
    public RestTemplate restTemplate() { return new RestTemplate(); }

}
